<template>
	<!-- #ifdef MP-WEIXIN -->
	<uv-navbar
	  :fixed="false"
	  :title="title"
	  left-arrow
	  @leftClick="$onClickLeft"
	/>
	<!-- #endif -->
	<view class="px-2 mt-2">
		<view class="bg-white p-2" >
			<uv-form :model="form" ref="uForm" >
				<uv-form-item>
						<view v-if="address.realName">
							<view>{{ address.address }} {{ address.detail }}</view>
							<text>{{ address.realName }} {{ address.phone }}</text>
						</view>
						<view v-else>请选择收货地址</view>
						<template #right>
							<uv-icon name="arrow-right" @click="chooseAddress"></uv-icon>
						</template>
				</uv-form-item>
			</uv-form>
		</view>
		<view class="bg-white p-2 mt-2">
			<view class="mb-5">积分商城</view>
			<view class="flex justify-between">
				<view class="flex">
					<image :src="product.image" mode="aspectFill" class="image"></image>
					<text class="font-size-medium">{{ product.title }}</text>
				</view>
				<view class="flex flex-column">
					<text class="font-size-medium" v-if="isOrigin == 1">{{ product.score }}积分 + {{ product.price }}元</text>
					<text class="font-size-medium" v-else>{{ product.otPrice }}元</text>
					<text class="font-size-medium text-color-assist mt-2 text-right">×1</text>
				</view>
			</view>
			<view class="flex justify-between mt-5" v-if="isOrigin == 1">
				<text class="font-size-medium">原价</text>
				<text class="font-size-medium" style="text-decoration: line-through;">{{ product.otPrice }}元</text>
			</view>
		</view>
	</view>
	<view class="buckle">
		<view class="discount big">
			<text class="title">平台优惠</text>
		</view>
		<view class="discount">
			<text class="title">商品总额</text>
			<view class="fares">
				{{ product.otPrice }}元
			</view>
		</view>
		<view class="discount">
			<text class="title">积分已省</text>
			<view class="fares cut">
				-{{ product.otPrice - product.price }}元
			</view>
		</view>
		<view class="discount">
			<text class="title">物流运费</text>
			<view class="fares">
				0元
			</view>
		</view>
	</view>
	<view>
		<view class="order">
			<view class="commodity">
				<text class="title">支付方式</text>
				<text class="pay-type">严选承保</text>
			</view>
			<view v-for="(pay,index) in payOptions" :key="index">
				<view class="method" :key="pay.id" @click="payType=pay.id">
					<image class="method_img" :src="pay.img" mode="widthFix"></image>
					<view class="payment">
						<view class="wx">
							<text class="title">{{pay.title}}</text>
							<view class="use">
								使用{{pay.title}}支付
								<text class="safety">{{pay.desc}}</text>
							</view>
						</view>
						<uni-icons v-if="payType==pay.id" type="circle-filled" size="23" color="#FF162E"></uni-icons>
						<uni-icons v-else type="circle" size="23" color="#ccc"></uni-icons>
					</view>
				</view>
			</view>
		</view>
	</view>
	<view class="fixed-bottom flex justify-between align-center bg-white ">
		<view class="mx-2 ont-weight-light" v-if="isOrigin == 1">合计:<text class="text-danger">{{ product.score }}积分 + {{ product.price }}元</text></view>
		<view class="mx-2 ont-weight-light" v-else>合计:<text class="text-danger">{{ product.otPrice }}元</text></view>
		<view><uv-button type="warning" color="#FF162E" :customStyle="customStyle" size="large" :text="isOrigin == 1 ? '立即兑换' : '立即购买'" @click="submit"></uv-button></view>
	</view>
	<uv-toast ref="uToast" />
</template>

<script setup>
import {
  ref,
  computed,
  getCurrentInstance
} from 'vue'
import { onReachBottom,onLoad,onPullDownRefresh} from '@dcloudio/uni-app'
import {
  scoreShopExchange,
  scoreShopDetail
} from '@/api/score'
import {
  payUnify
} from '@/api/order'
import cookie from '@/utils/cookie'
import { useMainStore } from '@/store/store'
import { storeToRefs } from 'pinia'
const { proxy } = getCurrentInstance();
const main = useMainStore()
const { address,isLogin} = storeToRefs(main)

const title = ref("确认订单")
const product = ref({})
const payOptions = ref([
	{
		id:1,
		title:'微信',
		desc:'安全·方便',
		img:''
	}
])
const payType = ref(1)
const isOrigin = ref(1) //0-原价 1-积分兑换

const customStyle = computed(() =>{
	return {
		  paddingLeft:'60rpx',
		  paddingRight:'60rpx'
		}
})

onLoad(() => {
	if(!isLogin.value) {
		uni.navigateTo({url: '/pages/components/pages/login/login'})
	}
	product.value = cookie.get('score_product')
	isOrigin.value =  cookie.get('is_origin')
	
})

// 选择地址
const chooseAddress = () => {
	uni.navigateTo({
		url: '/pages/components/pages/address/address?is_choose=true&scene=scoreShop'
	})
}

// 提交
const submit = async() => {
	if (!address.value.id) {
		proxy.$refs.uToast.show({
			message: '请选择收货地址',
			type: 'warning',
		})
		return
	}
	let data = await scoreShopExchange({
		productId: product.value.id,
		addressId: address.value.id,
		num: 1,
		isOrigin: isOrigin.value,
		payType: 'weixin'
	})
	

	if (data == '0') {
		cookie.remove('score_product')
		setTimeout(function() {
			uni.navigateTo({
				url: '/pages/components/pages/scoreproduct/order'
			})
		}, 1000)	
	}else{
		weixinPay(data)
	}
	
	
}

const weixinPay = async(orderId) => {
	let from = 'routine'
	// #ifdef H5
	from = 'h5'
	if(isWeixin()){
		from = 'wechat'
	}
	
	// #endif
	//let that = this;
	let data = await payUnify({
		uni: orderId,
		from: from,
		paytype: 'weixin'
	});

	if (data.trade_type == 'MWEB') {
		// #ifdef H5
		// 微信外的H5
		location.href = data.data;
		// #endif
	} else if (data.trade_type == 'JSAPI') {
		// #ifdef MP-WEIXIN
		uni.requestPayment({
			provider: 'wxpay',
			timeStamp: data.data.timeStamp,
			nonceStr: data.data.nonceStr,
			package: data.data.package,
			signType: 'MD5',
			paySign: data.data.paySign,
			success: function(res) {
				cookie.remove('score_product')
				uni.navigateTo({
					url: '/pages/components/pages/scoreproduct/order'
				})
			},
			fail: function(err) {
			}
		});
		// #endif
	} else if (data.trade_type == 'W-JSAPI'){
		//公众号支付
		let config = await getWechatConfig();
		if (config) {
		  jweixin.config({
				debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
		        appId: config.appId, // 必填，公众号的唯一标识
		        timestamp: config.timestamp, // 必填，生成签名的时间戳
		        nonceStr: config.nonceStr, // 必填，生成签名的随机串
		        signature: config.signature, // 必填，签名
		        jsApiList: [
		          'chooseWXPay'
		        ] ,
			 }
			);
		  jweixin.ready(function() {
		   jweixin.chooseWXPay({
			timestamp: data.data.timeStamp, 
			nonceStr: data.data.nonceStr, 
			package:  data.data.package, 
			signType: 'MD5', 
			paySign: data.data.paySign, 
			success: function(res) {
				 cookie.remove('score_product')
				 uni.navigateTo({
				 	url: '/pages/components/pages/scoreproduct/order'
				 })
			},
			fail: function(err) {
			}
		   });
		  });
		   jweixin.error(function(res) {

		  });
		 } else {
	  }
		
	}
}

</script>

<style lang="scss" scoped>
	.image {
		width: 160rpx;
		height: 160rpx;
		margin-right: 30rpx;
		border-radius: 8rpx;
	}
	.buckle{
		margin: 20rpx auto;
		background-color: #fff;
		position: relative;
		border-radius: 10rpx;
		padding: 15rpx 30rpx 30rpx;
		.discount{
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-weight: bold;
			margin-bottom: 10rpx;
			padding: 20rpx 0;
			&.big{
				font-size: $font-size-lg;
			}
			.cut{
				color: $theme-color;
			}
		}
	}
	.order{
		margin: 20rpx auto;
		background-color: #fff;
		position: relative;
		border-radius: 10rpx;
		.commodity{
			width: 95%;
			margin: 0 auto;
			display: flex;
			align-items: center;
			padding-top: 30rpx;
			font-size: $font-size-lg;
			.pay-type{
				background-color: #00b34a;
				padding: 0 10rpx;
				color: #fff;
				border-radius: 30rpx;
				font-size: 11px;
				margin-left: 10rpx;
			}
			
		}
		.title{
			font-weight: bold;
		}
		.method{
			width: 95%;
			margin: 0 auto;
			display: flex;
			align-items: center;
			.method_img{
				width: 80rpx;
				height: 80rpx;
				
			}			
			.payment{
				margin-left: 30rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				flex: 1;
				.wx{
					display: flex;
					flex-direction: column;
					justify-content: center;
					border-bottom: 1px solid #f5f5ff;
					padding: 40rpx 0;					
					.use{
						font-size: $font-size-sm;
						color: $text-color-grey;
						.safety{
							color: #FF162E;
							margin-left: 5rpx;
						}
					}
				}
			}
		}
	}
</style>